package com.btl.cygf;

import java.util.LinkedList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.btl.bean.ZuiXin;
import com.btl.utils.DownTuUtils;
import com.btl.utils.TimeUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yzx.yunyanzhengdemo.activity.LoginActivity;

public class ZuoZheActivity extends Activity implements OnClickListener {

	private ImageView login_backtofragment;
	private TextView fabuzhe;
	private ImageView zuoze_touxiang;
	private TextView zuoze_guanzhu;
	private TextView zuozhe_fansi;
	private TextView zuoze_plus_guanzhu;
	private TextView zuozhe_qianming;

	private PullToRefreshListView mListView;
	private LinkedList<ZuiXin> listItems = new LinkedList<ZuiXin>(); // 数据源集合
	private ArrayAdapter<String> mAdapter;
	private MyListAdapter myListAdapter;
	private AsyncHttpClient client;
	private RequestParams params;
	private int v_id;
	private int lastid;

	private LinearLayout guanzhu_layout;

	ImageLoader imageLoader = ImageLoader.getInstance();

	private String fid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.zuozhe_layout);

		initView();

	}

	private void initView() {
		login_backtofragment = (ImageView) findViewById(R.id.login_backtofragment);
		zuoze_touxiang = (ImageView) findViewById(R.id.zuoze_touxiang);
		login_backtofragment.setOnClickListener(this);
		fabuzhe = (TextView) findViewById(R.id.fabuzhe);
		zuoze_guanzhu = (TextView) findViewById(R.id.zuoze_guanzhu);
		zuozhe_fansi = (TextView) findViewById(R.id.zuozhe_fansi);
		zuoze_plus_guanzhu = (TextView) findViewById(R.id.zuoze_plus_guanzhu);
		zuozhe_qianming = (TextView) findViewById(R.id.zuozhe_qianming);

		guanzhu_layout = (LinearLayout) findViewById(R.id.guanzhu_layout);
		guanzhu_layout.setOnClickListener(this);

		client = new AsyncHttpClient();
		params = new RequestParams();
		Intent it = getIntent();
		fid = it.getStringExtra("id");
		System.out.println(fid + "zuozhe");
		imageLoader.init(DownTuUtils.getConfig(ZuoZheActivity.this));
		getInfo();

		getDataRefresh();

		mListView = (PullToRefreshListView) findViewById(R.id.list_zuozhe);

		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				if (mListView.isHeaderShown()) {
					// 下拉刷新
					getDataRefresh();
				} else if (mListView.isFooterShown()) {
					// 上拉加载
					if (v_id == lastid) {
						mListView.getLoadingLayoutProxy(false, true)
								.setRefreshingLabel("没有更多选项");
						// mListView.setMode(Mode.DISABLED);
						new GetDataTask().execute();
					} else {
						getDataMore(v_id);
					}
				}
			}
		});

		mListView.setMode(Mode.BOTH);
		mListView.getLoadingLayoutProxy(false, true).setPullLabel("加载完成");
		mListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载");
		mListView.getLoadingLayoutProxy(false, true).setReleaseLabel("上拉以加载");
		mListView.getRefreshableView().setAdapter(mAdapter);

		// listItems = getListItems();
		myListAdapter = new MyListAdapter();
		mListView.setAdapter(myListAdapter);

	}

	private void getInfo() {
		params.remove("fid");
		params.remove("pid");
		params.add("fid", fid);

		SharedPreferences share = getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);
		final String pid = share.getString("id", "");
		params.add("pid", pid);

		if (!pid.equals("")) {
			if (fid.equals(pid)) {
				guanzhu_layout.setVisibility(View.GONE);
			}

		}

		client.post(getResources().getString(R.string.url)
				+ "/CYGF/queryInfo.info", params,
				new JsonHttpResponseHandler() {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						JSONObject object = response.optJSONObject(0);
						imageLoader.displayImage(object.optString("avatar"),
								zuoze_touxiang, DownTuUtils.getOptions3());
						if (object.optString("nickname").equals("")) {
							fabuzhe.setText(fid);
						} else {
							fabuzhe.setText(object.optString("nickname"));
						}
						if (object.optString("guanzhu_flag").equals("已关注")) {
							zuoze_plus_guanzhu
									.setBackgroundColor(getResources()
											.getColor(R.color.lv));
							zuoze_plus_guanzhu.setText("已关注");
							zuoze_plus_guanzhu.setTextColor(Color.WHITE);

						}

						zuoze_guanzhu.setText(object.optString("guanzhu"));
						zuozhe_fansi.setText(object.optString("fansi"));

						zuozhe_qianming.setText(object.optString("intro"));

					}

				});

	}

	/**
	 * 连接到网络 获取数据
	 * 
	 * @param pagenow
	 */
	private void getDataRefresh() {
		params.remove("fid");
		params.remove("pid");
		params.remove("p_id");
		params.add("p_id", fid);
		// 实例LinkList数据源
		listItems = new LinkedList<ZuiXin>();
		// 连接查看分类（刷新）
		client.post(getResources().getString(R.string.url)
				+ "/CYGF/FaBuRefreshJSON", params,
				new JsonHttpResponseHandler() {
					// 链接成功做出的反应
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						for (int i = 0; i < response.length(); i++) {
							ZuiXin zuiXin = new ZuiXin();
							JSONObject object = response.optJSONObject(i);
							String s1 = object.optString("v_image");
							String s2 = object.optString("v_title");
							String s3 = object.optString("v_sort");
							String s4 = object.optString("v_jianjie");
							String s5 = object.optString("v_shijian");
							int s6 = object.optInt("v_id");
							zuiXin.setVid(s6);
							zuiXin.setPicture(s1);
							zuiXin.setTitle(s2);
							zuiXin.setSort(s3);
							zuiXin.setInfo(s4);
							zuiXin.setDate(s5);

							lastid = object.optInt("lastid");
							listItems.add(zuiXin);
							// listItems.addFirst(zuiXin);
							zuiXin = null;
							if (i == (response.length() - 1)) {
								v_id = Integer.parseInt(object
										.optString("v_id"));
							}
						}
						// BaseAdapter数据发生改变
						myListAdapter.notifyDataSetChanged();
						mListView.onRefreshComplete();
						super.onSuccess(statusCode, headers, response);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}

					// 链接网络失败，做出的反应
					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	/**
	 * 下拉加载更多
	 */
	private void getDataMore(final int vid) {
		params.remove("v_id");
		params.remove("p_id");
		params.add("v_id", vid + "");
		// params.add("p_id", p_id);
		// 连接查看分类（加载）
		client.post(getResources().getString(R.string.url)
				+ "/CYGF/FaBuMoreJSON", params, new JsonHttpResponseHandler() {
			// 链接成功做出的反应
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONArray response) {
				Log.i("vid", vid + "");
				Log.i("vid", lastid + "");
				if (vid == lastid) {
					mListView.getLoadingLayoutProxy(false, true)
							.setRefreshingLabel("没有更多选项");
					// mListView.setMode(Mode.DISABLED);
					new GetDataTask().execute();
				} else {
					for (int i = 0; i < response.length(); i++) {
						ZuiXin zuiXin = new ZuiXin();
						JSONObject object = response.optJSONObject(i);
						String s1 = object.optString("v_image");
						String s2 = object.optString("v_title");
						String s3 = object.optString("v_sort");
						String s4 = object.optString("v_jianjie");
						String s5 = object.optString("v_shijian");
						int s6 = object.optInt("v_id");
						zuiXin.setVid(s6);
						zuiXin.setPicture(s1);
						zuiXin.setTitle(s2);
						zuiXin.setSort(s3);
						zuiXin.setInfo(s4);
						zuiXin.setDate(s5);
						// listItems.addFirst(zuiXin);
						listItems.add(zuiXin);
						zuiXin = null;
						if (i == (response.length() - 1)) {
							v_id = Integer.parseInt(object.optString("v_id"));
						}
					}
					// BaseAdapter数据发生改变
					myListAdapter.notifyDataSetChanged();
					mListView.onRefreshComplete();

				}

				super.onSuccess(statusCode, headers, response);
			}

			// 链接网络失败，做出的反应
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONArray errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.guanzhu_layout:

			guanzhu();

			break;

		case R.id.login_backtofragment:
			finish();
			break;

		default:
			break;
		}

	}

	private void guanzhu() {
		String str = zuoze_plus_guanzhu.getText().toString();
		SharedPreferences share = getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);

		params.remove("fid");
		params.remove("pid");
		params.remove("p_id");
		params.remove("v_id");

		String pid = share.getString("id", "");
		if (str.equals("+ 关注")) {

			if (pid.equals("")) {
				startActivity(new Intent(ZuoZheActivity.this,
						LoginActivity.class));
			} else {
				params.add("pid", pid);
				params.add("fid", fid);
				client.post(getResources().getString(R.string.url)
						+ "/CYGF/insertFriend.info", params,
						new JsonHttpResponseHandler() {

							@Override
							public void onFailure(int statusCode,
									Header[] headers, Throwable throwable,
									JSONArray errorResponse) {
								// TODO Auto-generated method stub
								super.onFailure(statusCode, headers, throwable,
										errorResponse);
							}

							@Override
							public void onSuccess(int statusCode,
									Header[] headers, JSONArray response) {

								JSONObject object = response.optJSONObject(0);
								String result = object.optString("msg");
								if (result.equals("关注成功")) {
									zuoze_plus_guanzhu
											.setBackgroundColor(getResources()
													.getColor(R.color.lv));
									zuoze_plus_guanzhu.setText("已关注");
									zuoze_plus_guanzhu
											.setTextColor(Color.WHITE);
								} else {
									Toast.makeText(getApplicationContext(),
											"关注失败", 1).show();
								}

							}

						});
			}
		} else {
			params.add("pid", pid);
			params.add("fid", fid);
			client.post(getResources().getString(R.string.url)
					+ "/CYGF/deleteFriend.info", params,
					new JsonHttpResponseHandler() {

						@Override
						public void onFailure(int statusCode, Header[] headers,
								Throwable throwable, JSONArray errorResponse) {
							// TODO Auto-generated method stub
							super.onFailure(statusCode, headers, throwable,
									errorResponse);
						}

						@Override
						public void onSuccess(int statusCode, Header[] headers,
								JSONArray response) {

							JSONObject object = response.optJSONObject(0);
							String result = object.optString("msg");
							if (result.equals("取消关注成功")) {
								zuoze_plus_guanzhu
										.setBackgroundColor(Color.WHITE);
								zuoze_plus_guanzhu.setText("+ 关注");
								zuoze_plus_guanzhu.setTextColor(getResources()
										.getColor(R.color.lv));
							} else {
								Toast.makeText(getApplicationContext(),
										"取消关注失败", 1).show();
							}

						}

					});
		}

	}

	/**
	 * listview的适配器MyListAdapter
	 */
	private class MyListAdapter extends BaseAdapter {

		class ListItemView {
			public ImageView touxiang;
			public TextView zuozhe;
			public TextView sort;
			public ImageView image;
			public TextView title;
			public TextView jianjie;
			public TextView shijian;
		}

		@Override
		public int getCount() {
			return listItems.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent intent = new Intent();
					intent.setClass(ZuoZheActivity.this, TieZiActivity.class);
					intent.putExtra("v_id", listItems.get(position - 1)
							.getVid() + "");
					Log.i("v_id", listItems.get(position - 1).getVid() + "");
					startActivity(intent);
				}
			});

			// final int selectID = position;
			// 自定义视图
			ListItemView listItemView = null;
			if (convertView == null) {
				listItemView = new ListItemView();
				// 获取list_item布局文件的视图
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.fabu_item_list, null);
				// 获取控件对象
				listItemView.touxiang = (ImageView) convertView
						.findViewById(R.id.touxiang);
				listItemView.zuozhe = (TextView) convertView
						.findViewById(R.id.zuozhe);
				listItemView.image = (ImageView) convertView
						.findViewById(R.id.img);
				listItemView.title = (TextView) convertView
						.findViewById(R.id.title);
				listItemView.jianjie = (TextView) convertView
						.findViewById(R.id.jian_jie);
				listItemView.shijian = (TextView) convertView
						.findViewById(R.id.shi_jian);
				listItemView.sort = (TextView) convertView
						.findViewById(R.id.sort);

				listItemView.touxiang.setVisibility(View.GONE);
				listItemView.zuozhe.setVisibility(View.GONE);

				// 设置控件集到convertView
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}

			// 设置文字和图片
			ImageLoader imageLoader = ImageLoader.getInstance();

			imageLoader.init(DownTuUtils.getConfig(ZuoZheActivity.this));

			imageLoader.displayImage(listItems.get(position).getPicture(),
					listItemView.image, DownTuUtils.getOptions());

			// listItemView.image.setImageBitmap(new
			// BitmapFactory().decodeByteArray(data, offset, length))
			listItemView.title.setText(listItems.get(position).getTitle());
			listItemView.sort.setText(listItems.get(position).getSort());
			listItemView.jianjie.setText(listItems.get(position).getInfo());
			listItemView.shijian.setText(TimeUtils.getDate(listItems.get(
					position).getDate()));
			return convertView;
		}

	}

	private class GetDataTask extends AsyncTask<Void, Void, String> {

		// 后台处理部分
		@Override
		protected String doInBackground(Void... params) {
			// Simulates a background job.
			// mListView.getLoadingLayoutProxy(false,
			// true).setRefreshingLabel("没有更多选项");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
			String str = "Added after refresh...I add";
			return str;
		}

		// 这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中
		// 根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值
		@Override
		protected void onPostExecute(String result) {

			// 通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合
			// myListAdapter.notifyDataSetChanged();
			// 32tCall onRefreshComplete when the list has been refreshed.
			mListView.onRefreshComplete();
			super.onPostExecute(result);
		}

	}

}
